# coding=utf-8
__author__ = 'Jiang Le'
from tools import Tools
import os
import json


# def filter(path_list):
#     for path in path_list:
#         if not os.path.exists(path):
#             path_list.remove(path)
#
#     return path_list


class Compiror():
    @staticmethod
    def initCompire(src):
        p = os.path.join(src, ".sunjian")
        d = {}
        with open(os.path.join(p, "list.json"), "r") as f:
            string = f.read()
        if string:
            d = json.loads(string)
        # 软件关闭前同步文件夹最后的状态
        old_keys = d.keys()
        # 同步文件夹目前的状态
        # 已确认下面三个均为unicode
        new_keys = Tools.getAllFilesIngored(src)
        delete_keys = Tools.cmpDelFiles(old_keys, new_keys)
        add_keys = Tools.cmpAddFiles(old_keys, new_keys)
        # 移除删除了的文件路径
        for key in delete_keys:
            d.pop(key)
        Tools.update_delete(src, delete_keys)
        # 添加新加的文件路径
        update_keys = d.keys()
        for key in add_keys:
            update_keys.append(key)
        add_path_list = []
        # 比较json中文件的hash与当前文件的hash值，如果不相同则更新json中的内容
        for key in update_keys:
            new_hash = Tools.hashContent(Tools.add_prefix(src, key))
            old_hash = d.get(key)
            # 如果在旧的dict中不存在key，或者旧的hash和新的hash不相等，则更新dict并且添加到add_path_list中
            if not old_hash or new_hash != old_hash.get("hash"):
                if old_hash and new_hash != old_hash.get("hash"):
                    d.pop(key)
                info = Tools.getFileInfo(src, Tools.add_prefix(src, key))
                d.update(info)
                add_path_list.append(key)
        Tools.update_add(src, add_path_list)
        json.dump(d, open(os.path.join(p, "list.json"), "w"))
